import mongoose from './index';
import chalk from 'chalk';

const Schema = mongoose.Schema;

interface OrderDocument extends Document {
  id: string;
  name: string;
  icon: string;
  deleted?: boolean;
}

const categorySchema = new Schema({
  id: {
    type: Number,
    default: 0,
  },
  name: String,
  icon: String,
  deleted: {
    type: Boolean,
    default: false,
  },
});

const Model: mongoose.Model<OrderDocument> = mongoose.model(
  'Categories',
  categorySchema
);

class Category {
  // 查询
  async query(obj = {}): Promise<any> {
    const res = await Model.find(obj);
    console.log(chalk.red(111));
    console.log(res);
    return res;
  }

  async update(obj): Promise<any> {
    const { _id } = obj;

    const res = await Model.findById(_id);
    if (!res) throw Error('未找到对应记录');
    Object.assign(res, obj);
    res.save();
  }

  async save(obj): Promise<any> {
    const count = await Model.count();
    const m = new Model({ ...obj, id: count });
    const res = await m.save();
    return res;
  }

  async delete(obj): Promise<any> {
    const { _id, id } = obj;
    const res = await Model.findOne({ id });
    if (!res) throw Error('未找到对应的记录');
    res.deleted = true;
    res.save();
  }
}

export default new Category();
